package top.wkl.springboot3.service.impl;

import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import top.wkl.springboot3.base.R;
import top.wkl.springboot3.entity.TbFiles;
import top.wkl.springboot3.entity.user.AuthInfo;
import top.wkl.springboot3.exception.AppException;
import top.wkl.springboot3.interceptor.AppInterceptor;
import top.wkl.springboot3.mapper.TbFilesMapper;
import top.wkl.springboot3.service.TbFilesService;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
@Slf4j
@Transactional
@RequiredArgsConstructor
public class TbFilesServiceImpl implements TbFilesService {
    private final TbFilesMapper tbFilesMapper;

    @Override
    public R<TbFiles> upload(MultipartFile file) {
        if (file == null) {
            return R.fail("文件为空", null);
        }
        //保存文件信息到数据库
        TbFiles files = new TbFiles();
        files.setFileName(file.getOriginalFilename().replaceAll("\\s", ""));
        files.setFileSize(file.getSize());
        files.setContentType(file.getContentType());
        AuthInfo authInfo = AppInterceptor.getAuthInfo();
        files.setUserId(authInfo.getId());

        int i = tbFilesMapper.insert(files);
        if (i != 1) {
            return R.fail("无法保存数据库，文件上传失败", null);
        }
        //保存文件到本地
        File dir = new File(UPLOAD_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filename = String.format("_%s_%s", files.getId(), files.getFileName());
        try {
            InputStream is = file.getInputStream();
            OutputStream os = new FileOutputStream(new File(dir, filename));
            byte[] buffer = new byte[8 * 1024];
            int len = is.read(buffer);
            while (len != -1) {
                os.write(buffer, 0, len);
                len = is.read(buffer);
                os.flush();
            }
            os.close();
            is.close();
            return R.ok("文件上传成功", files);

        } catch (Exception e) {
            throw AppException.getInstance(e.getMessage());
        }
    }

    @Override
    public void download(Integer id, HttpServletResponse response) {
        TbFiles files = tbFilesMapper.selectById(id);
        if (files == null) {
            throw AppException.getInstance("文件不存在");
        }
        String filename = String.format("_%s_%s", files.getId(), files.getFileName());
        try {
            response.sendRedirect(FILE_URL + URLEncoder.encode(filename, StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw AppException.getInstance(e.getMessage());
        }

//        File dir = new File(UPLOAD_DIR);
//        String filename = String.format("_%s_%s", files.getId(), files.getFileName());
//        File file = new File(dir, filename);
//        if (!file.exists()) {
//            throw AppException.getInstance("文件不存在");
//        }
//        try {
//            byte[] buffer = files.getFileName().getBytes("UTF-8");
//            String urlname = new String(buffer, "ISO8859-1");
//            response.reset();
//            response.setContentType(files.getContentType());
//            response.setHeader("Content-Disposition", "attachment;filename=" + urlname);
//            response.setContentLengthLong(files.getFileSize());
//            InputStream is = new FileInputStream(file);
//            OutputStream os = response.getOutputStream();
//            byte[] nbuffer = new byte[8 * 1024];
//            int len = is.read(nbuffer);
//            while (len != -1) {
//                os.write(nbuffer, 0, len);
//                len = is.read(nbuffer);
//                os.flush();
//            }
//            os.close();
//            is.close();
//
//        } catch (Exception ex) {
//            throw AppException.getInstance(ex.getMessage());
//        }
    }
}
